package cn.just.student_mall.service;

import cn.just.student_mall.entity.Address;
import cn.just.student_mall.mapper.AddressMapper;
import cn.just.student_mall.service.ex.AddressCountMaxException;
import cn.just.student_mall.service.ex.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author wujiaming
 * @Description TODO
 * @Date 2021-03-25 15:25
 * @Version 1.0
 */
@Service
public class AddressService {

    @Value("${project.address-max-count}")
    private int addressMaxCount;

    @Autowired
    AddressMapper addressMapper;

    public void addNew(Integer uid, String username, Address address)
        throws InsertException, AddressCountMaxException {

        System.out.println("addressMaxCount=" + addressMaxCount);
        //根据uid获取收货地址的数量
        //判断数量 是否 达到上线
        Integer count = addressMapper.countByUid(uid);
        if(count>=6){
            throw new AddressCountMaxException();
        }

        //根据以上的数量是否为0，得到isDefaul值 0-默认 1-默认
        Integer isDefault = count==0 ? 1:0;
        //补全address数据
        address.setIsDefault(isDefault);
        address.setUid(uid);
        address.setCreatedUser(username);
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());

        //插入数据
        Integer row = addressMapper.insertAddress(address);
        if(row != 1){
            throw new InsertException();
        }
    }
}
